/**
 * 通过eventBus 监听baseForm中name、nameCn字段变化
 * 发生改变时触发 change-name 事件
 * FlowEdit 在onMounted阶段注册了监听change-name
 * 当事件触发时，修改needReRender的值为true
 * 当进入FlowEdit页面时，needReRender为true则重新绘制页面
 * 
 * 陶俊 2022-5-11
 */
import { defineComponent, ref, computed, onMounted, onActivated, nextTick } from "vue";
import BpmnEditor from "@/components/BpmnEditor";
import defaultBpmnXml from '@/components/BpmnEditor/bpmn/defaultBpmnXml.ts'
import eventBus from '../eventbus'

export default defineComponent({
  name: "FlowEdit",
  props: {
    modelValue: {
      type: Object,
      default: () => { }
    }
  },
  setup (props, { emit }) {
    const needReRender = ref(false)
    const visible = ref(true)
    let parser = new DOMParser(); // xml解析器

    const xml = computed({
      get: () => {
        // 确保xml中'bpmn2:process'节点的id、name属性与baseFrom的name、nameCn对应
        if (props.modelValue.xml) {
          let xmlDoc = parser.parseFromString(props.modelValue.xml, "text/xml")
          let process = xmlDoc.getElementsByTagName('bpmn2:process')
          process[0].setAttribute('id', props.modelValue.name || 'Process_1')
          process[0].setAttribute('name', props.modelValue.nameCn || 'Process_1')
          return new XMLSerializer().serializeToString(xmlDoc)
        }
        return defaultBpmnXml(props.modelValue.name || 'Process_1', props.modelValue.nameCn || 'Process_1')
      },
      set: val => {
        let xmlDoc = parser.parseFromString(val, "text/xml");
        let process = xmlDoc.getElementsByTagName('bpmn2:process')
        emit('update:modelValue', {
          ...props.modelValue,
          name: process[0].getAttribute('id'),
          nameCn: process[0].getAttribute('name'),
          xml: val
        })
      }
    })

    onMounted(() => {
      eventBus.$on('change-name', () => {
        needReRender.value = true
      })
    })
    onActivated(() => {
      if (needReRender.value) {
        visible.value = false
        needReRender.value = false
        nextTick(() => {
          visible.value = true
        })
      }
    })

    return () => <>
      {visible.value ? <BpmnEditor
        v-model:xml={xml.value}
      /> : <div></div>}
    </>
  }
});
